package com.kuaidu.ll.quickreadnews.manager;

import android.app.Activity;
import android.support.v4.app.ActivityCompat;

import java.util.Stack;

/**
 * Created by liulei on 2017/7/5.
 * activity stack的维护类
 */

public class ActivityStackManager {

    private static volatile ActivityStackManager mInstance;
    private static Stack<Activity> mActivityStack;

    private ActivityStackManager() {
        mActivityStack = new Stack<>();
    }

    public static ActivityStackManager getInstance() {
        if (mInstance == null) {
            synchronized (ActivityStackManager.class) {
                if (mInstance == null) {
                    mInstance = new ActivityStackManager();
                }
            }
        }
        return mInstance;
    }

    /**
     * 获得activity栈中 栈顶activity
     *
     * @return Activity 返回一个activity
     */
    public Activity getCurrentActivity() {
        if (mActivityStack == null || mActivityStack.size() == 0) {
            return null;
        }
        return mActivityStack.lastElement();
    }

    /**
     * 获得当前任务栈的容量
     *
     * @return int 任务栈中activity的数量
     */
    public int getActivityStackSize() {
        return mActivityStack.size();
    }

    /**
     * 将activity添加到栈中
     *
     * @param activity
     */
    public void addActivity(Activity activity) {
        mActivityStack.add(activity);
    }

    /**
     * 移除栈顶的activity
     */
    public void removeActivity() {
        removeActivity(mActivityStack.lastElement());
    }

    /**
     * 移除指定的activity
     *
     * @param activity
     */
    public void removeActivity(Activity activity) {

        if (activity !=null){
            if (!activity.isFinishing()){
                activity.finish();
            }
            mActivityStack.remove(activity);
            activity = null;
        }
    }

    /**
     * 移除指定类的activity
     * @param clazz 传入需要移除的activity类
     */
    public void removeActivity(Class<?> clazz){
        for (Activity activity : mActivityStack){
            removeActivity(clazz);
        }
    }

    /**
     * 移除activity栈中所有的activity
     */
    public void removeAllActivity() {
        for (int i = 0; i < mActivityStack.size(); i++) {
            Activity activity = mActivityStack.get(i);
            if (activity !=null){
                if (!activity.isFinishing()){
                    activity.setResult(Activity.RESULT_CANCELED);
                    ActivityCompat.finishAffinity(activity);
                }
            }
        }
        mActivityStack.clear();
    }
}
